﻿using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Text;
using QXBook.Utils;
using QXBook.Model;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace QXBook.Service
{
    public class AdminService : ServiceBase
    {
        /// <summary>
        /// 管理员登陆函数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public string AdminLogin(string adminname, string pwd)
        {
            MembersInfo admininfo = this.GetAdminEntityByAdminName(adminname);

            //用户不存在
            if (admininfo == null || admininfo.IsDelete == YesNo.Yes)
            {
                return MsgConst.ADMIN_LOST;
            }

            if (admininfo.IsOnline == YesNo.Yes && admininfo.LastLoginIp != CommonUtils.GetIP())
            {
                return MsgConst.ADMIN_ISLOCK;
            }

            //用户密码错误
            if (admininfo.Password != CommonUtils.MD5(pwd))
            {
                return MsgConst.ADMIN_USERORPWDERROR;
            }

            //用户已经被锁定
            if (admininfo.IsLock == YesNo.Yes)
            {
                return MsgConst.ADMIN_ISLOCK;
            }

            admininfo.IsOnline = YesNo.Yes;

            DbCommand cmd = new SqlCommand("UPDATE Members SET IsOnline=@IsOnline,LastLoginIp='" + CommonUtils.GetIP() + 
               "',LoginCount=LoginCount+1,LastLoginDate=GETDATE() WHERE AdminName=@AdminName");
            base.db.AddInParameter(cmd, "@IsOnline", DbType.Int16, (int)admininfo.IsOnline);
            base.db.AddInParameter(cmd, "@AdminName", DbType.String, admininfo.AdminName);
            base.db.ExecuteNonQuery(cmd);
            //DataBaseFactory.AdminHandlers.AdminLogin(admininfo, pwd);

            HttpCookie admincookie = Cookie.Get(ConfigurationManager.AppSettings["AdminCookieName"]);
            if (admincookie == null)
            {
                admincookie = Cookie.Set(ConfigurationManager.AppSettings["AdminCookieName"]);
            }
            admincookie.Values["AdminName"] = HttpContext.Current.Server.UrlEncode(adminname);
            Cookie.Save(admincookie);

            object TempAdmin = SessionState.Get(ConfigurationManager.AppSettings["AdminSessionName"]);
            if (TempAdmin != null)
            {
                SessionState.Remove(ConfigurationManager.AppSettings["AdminSessionName"]);
            }

            CachingService.Remove(CachingService.CACHING_ALL_ADMIN_ENTITY);
            return MsgConst.OK;
        }
        /// <summary>
        /// 获取管理员
        /// </summary>
        /// <param name="keypar"></param>
        /// <returns></returns>
        public MembersInfo GetModel(object keypar)
        {
            DataSet ds = base.db.ExecuteDataSet(CommandType.Text, "SELECT TOP 1 MemberID,AdminName,NickName,PassWord,RoleID,PopDomList,IsLock,IsDelete,IsOnline,LastLoginIp FROM Members WHERE MemberID=" + keypar.ToString());
            if (ds == null || ds.Tables.Count == 0)
            {
                return null;
            }

            if (ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }

            MembersInfo member = new MembersInfo();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                member.MemberID = CommonUtils.ToInt(dr["MemberID"]);
            }

            return member;
        }
        
        /// <summary>
        /// 根据管理员姓名获得管理员信息
        /// </summary>
        /// <param name="adminname"></param>
        /// <returns></returns>
        public MembersInfo GetAdminEntityByAdminName(string adminname)
        {
            Dictionary<string, MembersInfo> allamdin = this.GetAllAdminEntity();
            if (allamdin == null) return null;
            if (allamdin.ContainsKey(adminname))
            {
                return allamdin[adminname];
            }
            return null;
        }

        /// <summary>
        /// 从管理员记录行中得到管理员实体
        /// </summary>
        /// <param name="Row"></param>
        /// <returns></returns>
        public MembersInfo GetAdminEntityFromDataRow(DataRow Row)
        {
            if (Row == null) return null;
            MembersInfo admininfo = new MembersInfo();
            admininfo.AdminName = Row["AdminName"].ToString();
            admininfo.NickName = Row["NickName"].ToString();
            admininfo.Password = Row["Password"].ToString();
            admininfo.Role = ServiceFactory.CreateInstance<AdminRuleService>().GetAdminRoleInfoByRoleId((int)Row["RoleID"]);
            admininfo.PopeDomList = ServiceFactory.CreateInstance<AdminRuleService>().GetAdminPopDomsByID(admininfo.Role, Row["PopDomList"].ToString());
            admininfo.PopDomStr = Row["PopDomList"].ToString();
            admininfo.IsLock = (YesNo)CommonUtils.ToInt(Row["IsLock"].ToString());
            admininfo.IsDelete = (YesNo)CommonUtils.ToInt(Row["IsDelete"].ToString());
            admininfo.IsOnline = (YesNo)CommonUtils.ToInt(Row["IsOnline"].ToString());
            admininfo.LastLoginIp = Row["LastLoginIp"].ToString();
            return admininfo;
        }

        /// <summary>
        /// 获得所有管理员实体
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, MembersInfo> GetAllAdminEntity()
        {
            Dictionary<string, MembersInfo> alladmin = (Dictionary<string, MembersInfo>)CachingService.Get(CachingService.CACHING_ALL_ADMIN_ENTITY);
            if (alladmin == null)
            {
                DataTable dt = this.GetAllAdmin();
                if (dt == null) return null;
                if (dt.Rows.Count == 0) return null;
                alladmin = new Dictionary<string, MembersInfo>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    MembersInfo admin = this.GetAdminEntityFromDataRow(dt.Rows[i]);
                    alladmin.Add(admin.AdminName, admin);
                }
                CachingService.Set(CachingService.CACHING_ALL_ADMIN_ENTITY, alladmin, null);
            }
            return alladmin;
        }

        /// <summary>
        ///获得指定管理员的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable GetAllAdmin()
        {
            string sql = "SELECT AdminName,NickName,PassWord,RoleID,PopDomList,IsLock,IsDelete,IsOnline,LastLoginIp FROM Members";
            DataSet ds = base.db.ExecuteDataSet(CommandType.Text, sql);
            return ds != null ? ds.Tables[0] : null;
        }

        /// <summary>
        /// 添加新的管理员
        /// </summary>
        /// <param name="vcAdminName"></param>
        /// <param name="nickname"></param>
        /// <param name="vPassWord"></param>
        /// <param name="iRole"></param>
        /// <param name="slock"></param>
        /// <param name="filesysroot"></param>
        /// <returns></returns>
        public string AddAdmin(string AdminName, MembersInfo OtherAdmin)
        {
            MembersInfo admininfo = this.GetAdminEntityByAdminName(AdminName);
            //判断当前管理员是否存在
            string rtmessage = this.CheckAdminPower(admininfo);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            DbCommand cmd = new SqlCommand();
            cmd.CommandText = @"INSERT INTO Members (AdminName,NickName,PassWord,RoleID,IsLock,PopDomList,AddDate)
                                VALUES(@AdminName,@NickName,@PassWord,@RoleID,@IsLock,@PopDomList,GETDATE())";

            base.db.AddInParameter(cmd, "@AdminName", DbType.String, OtherAdmin.AdminName);
            base.db.AddInParameter(cmd, "@NickName", DbType.String, OtherAdmin.NickName);
            base.db.AddInParameter(cmd, "@PassWord", DbType.String, OtherAdmin.Password);
            base.db.AddInParameter(cmd, "@RoleID", DbType.Int32, OtherAdmin.RoleID);
            base.db.AddInParameter(cmd, "@IsLock", DbType.Int16, (int)OtherAdmin.IsLock);
            base.db.AddInParameter(cmd, "@PopDomList", DbType.String, OtherAdmin.PopDomStr);
            base.db.ExecuteNonQuery(cmd);

            this.AminInfoRefash();
            return string.Empty;
        }

        /// <summary>
        /// 更新管理员信息
        /// </summary>
        /// <param name="admin"></param>
        /// <param name="vcAdminName"></param>
        /// <param name="nickname"></param>
        /// <param name="vPassWord"></param>
        /// <param name="iRole"></param>
        /// <param name="clock"></param>
        /// <param name="vcPopedom"></param>
        /// <param name="classpop"></param>
        /// <returns></returns>
        public string UpdateAdminInfo(string AdminName, MembersInfo OtherAdmin)
        {
            MembersInfo admininfo = this.GetAdminEntityByAdminName(AdminName);
            //判断当前管理员是否存在
            string rtmessage = this.CheckAdminPower(admininfo);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            string SQL = "UPDATE admin SET ";

            if (!string.IsNullOrEmpty(OtherAdmin.Password))
            {
                SQL += "PassWord=@PassWord,";
            }

            SQL += "NickName=@NickName,RoleID=@RoleID,IsLock=@IsLock,PopDomList=@PopDomList,UpdateDate=GETDATE() WHERE MemberID=@MemberID";

            DbCommand cmd = new SqlCommand(SQL);
            base.db.AddInParameter(cmd, "@PassWord", DbType.String, OtherAdmin.Password);
            base.db.AddInParameter(cmd, "@NickName", DbType.String, OtherAdmin.NickName);
            base.db.AddInParameter(cmd, "@RoleID", DbType.Int32, OtherAdmin.RoleID);
            base.db.AddInParameter(cmd, "@IsLock", DbType.Int16, (int)OtherAdmin.IsLock);
            base.db.AddInParameter(cmd, "@PopDomList", DbType.String, OtherAdmin.PopDomStr);
            base.db.AddInParameter(cmd, "@MemberID", DbType.Int32, OtherAdmin.MemberID);
            base.db.ExecuteNonQuery(cmd);

            this.AminInfoRefash();
            return string.Empty;
        }

        public void AminInfoRefash()
        {
            base.db.ExecuteNonQuery(CommandType.Text, "UPDATE [Members] SET IsOnline=" + (int)YesNo.No + " WHERE DATEDIFF(n,LastLoginDate,GETDATE())>30");
            CachingService.Remove(CachingService.CACHING_ALL_ADMIN_ENTITY);
        }

        /// <summary>
        /// 删除管理员(wait for mdy)
        /// </summary>
        /// <param name="AdminID"></param>
        /// <returns></returns>
        public int DeleteAdminById(int AdminID)
        {
            if (AdminID == 0) return 0;
            string sql = "DELETE FROM Members WHERE MemberID=" + AdminID.ToString();
            return base.db.ExecuteNonQuery(CommandType.Text, sql);
        }

        /// <summary>
        /// 更改自己的登陆信息
        /// </summary>
        /// <param name="adminname"></param>
        /// <param name="oldpwd"></param>
        /// <param name="npwd"></param>
        /// <param name="nickname"></param>
        /// <returns></returns>
        public string ChanageAdminLoginInfo(string adminname, string oldpwd, string npwd, string nickname)
        {
            MembersInfo admininfo = this.GetAdminEntityByAdminName(adminname);

            string rtmessage = this.CheckAdminPower(admininfo);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            //输入原始密码不正确
            if(oldpwd!=admininfo.Password)
            {
                return MsgConst.ADMIN_CHANGE_PASSERROR;
            }
     
            //您的帐号已经锁定，不能修改登陆信息
            if (admininfo.IsLock == YesNo.Yes)
            {
                return MsgConst.ADMIN_CHANGE_ISLOCK;
            }

            DbCommand cmd = new SqlCommand();
            if (string.IsNullOrEmpty(npwd))
            {
                cmd.CommandText = "UPDATE Members SET NickName=@NickName WHERE AdminName=@AdminName";
                base.db.AddInParameter(cmd, "@NickName", DbType.String, nickname);
                base.db.AddInParameter(cmd, "@AdminName", DbType.String, admininfo.AdminName);
            }
            else
            {
                cmd.CommandText = "UPDATE Members SET NickName=@NickName, Password=@Password WHERE AdminName=@AdminName";
                base.db.AddInParameter(cmd, "@NickName", DbType.String, nickname);
                base.db.AddInParameter(cmd, "@Password", DbType.String, npwd);
                base.db.AddInParameter(cmd, "@AdminName", DbType.String, admininfo.AdminName);
            }

            return string.Empty;
        }

        public string CheckAdminPower(MembersInfo admininfo)
        {
            //-操作员为空，您是否尚未登陆？
            if (string.IsNullOrEmpty(admininfo.AdminName))
            {
                return MsgConst.ADMIN_ISNULL;
            }

            //您不并不在线，您是否尚未登陆？
            if (admininfo.IsOnline != YesNo.Yes)
            {
                return MsgConst.ADMIN_ISNULL;
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取角色下的管理员列表信息
        /// </summary>
        /// <param name="iRoleID"></param>
        /// <param name="admincount"></param>
        /// <param name="rolecount"></param>
        /// <param name="rolename"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public int GetAdminList(int RoleID, ref int admincount, ref int rolecount, ref string rolename, ref DataSet ds)
        {
            if (RoleID == 0)
            {
                rolename = "所有管理员";
                admincount = CommonUtils.ToInt(base.db.ExecuteScalar(CommandType.Text, "SELECT COUNT(1) FROM Members WHERE IsDelete<>" + (int)YesNo.Yes));
                ds = base.db.ExecuteDataSet(CommandType.Text, "SELECT A.MemberID,A.AdminName,A.NickName,A.IsLock,A.AddDate,A.UpdateDate,B.RoleName,B.RoleID "
                                            + "FROM Members A JOIN MembersRole B ON A.RoleID = B.RoleID WHERE A.IsDelete<>" + (int)YesNo.Yes);
            }
            else if (RoleID > 0)
            {
                rolename = CommonUtils.ToString(base.db.ExecuteScalar(CommandType.Text, "SELECT TOP 1 RoleName FROM MembersRole WHERE RoleID=" + RoleID.ToString()));
                admincount = CommonUtils.ToInt(base.db.ExecuteScalar(CommandType.Text, "SELECT COUNT(1) FROM Members WHERE RoleID=" + RoleID.ToString() + " AND IsDelete <>" + (int)YesNo.Yes));

                ds = base.db.ExecuteDataSet(CommandType.Text, "SELECT A.MemberID,A.AdminName,A.NickName,A.IsLock,A.AddDate,A.UpdateDate,B.RoleName,B.RoleID "
                                            + "FROM Members A JOIN MembersRole B ON A.RoleID = B.RoleID WHERE A.RoleID=" + RoleID.ToString() + " AND A.IsDelete<>" + (int)YesNo.Yes);
            }
            else if (RoleID == -1)
            {

                rolename = "管理员回收站";
                admincount = CommonUtils.ToInt(base.db.ExecuteScalar(CommandType.Text, "SELECT COUNT(1) FROM Members WHERE IsDelete=" + (int)YesNo.Yes));

                ds = base.db.ExecuteDataSet(CommandType.Text, "SELECT A.MemberID,A.AdminName,A.NickName,A.IsLock,A.AddDate,A.UpdateDate,B.RoleName,B.RoleID "
                                            + "FROM Members A JOIN MembersRole B ON A.RoleID = B.RoleID WHERE A.IsDelete=" + (int)YesNo.Yes);
            }

            return 1;
        }

        /// <summary>
        /// 移动管理员到管理组
        /// </summary>
        /// <param name="vcAdminname"></param>
        /// <param name="admins"></param>
        /// <param name="irole"></param>
        /// <returns></returns>
        public string AdminChangeGroup(string Adminname, string admins, int roleID)
        {
            MembersInfo admininfo = this.GetAdminEntityByAdminName(Adminname);

            //判断当前管理员是否存在
            string rtmessage = this.CheckAdminPower(admininfo);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            //组编号不正确
            if (roleID == 0)
            {
                return MsgConst.ADMINROLE_ERROR;
            }

            if (admins.IndexOf(",") > -1)
            {
                base.db.ExecuteNonQuery(CommandType.Text, "UPDATE admin SET iRole = " + roleID.ToString()
                    + " WHERE vcAdminName IN (" + admins + ")");
            }
            else
            {
                admins = admins.Replace("'", "");
                base.db.ExecuteNonQuery(CommandType.Text, "UPDATE admin SET iRole = " + roleID.ToString()
                    + " WHERE vcAdminName = '" + admins + "'");
            }
            return string.Empty;
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="vcAdminname"></param>
        /// <param name="admins"></param>
        /// <param name="action">01，逻辑删除 02物理删除 03救回管理员</param>
        /// <returns></returns>
        public int DelAdmins(string Adminname, string adminIds, AdminDeleteMod action)
        {
            MembersInfo admin = this.GetAdminEntityByAdminName(Adminname);
            if (admin == null) return -19000000;

            int result = 0;
            if (action == AdminDeleteMod.Logic)
            {
                if (adminIds.IndexOf(",") > -1)
                {
                    result = base.db.ExecuteNonQuery(CommandType.Text, "UPDATE Members SET IsDelete=" + (int)YesNo.Yes + " WHERE MemberID IN (" + adminIds + ") ");
                }
                else
                {
                    result = base.db.ExecuteNonQuery(CommandType.Text, "UPDATE Members SET IsDelete=" + (int)YesNo.Yes + " WHERE MemberID=" + adminIds);
                }
            }
            else if (action == AdminDeleteMod.Physical)
            {
                if (adminIds.IndexOf(",") > -1)
                {
                    result = base.db.ExecuteNonQuery(CommandType.Text, "DELETE FROM Members WHERE MemberID IN (" + adminIds + ") ");
                }
                else
                {
                    result = base.db.ExecuteNonQuery(CommandType.Text, "DELETE FROM Members WHERE MemberID=" + adminIds);
                }
            }

            return result;
        }

        public int ReSaveAdmin(string Adminname, string adminIds)
        {
            MembersInfo admin = this.GetAdminEntityByAdminName(Adminname);
            if (admin == null) return -19000000;

            int result = 0;
            if (adminIds.IndexOf(",") > -1)
            {
                result = base.db.ExecuteNonQuery(CommandType.Text, "UPDATE Members SET IsDelete=" + (int)YesNo.No + " WHERE MemberID IN (" + adminIds + ")");
            }
            else
            {
                result = base.db.ExecuteNonQuery(CommandType.Text, "UPDATE Members SET IsDelete=" + (int)YesNo.No + " WHERE MemberID=" + adminIds);
            }

            return result;
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <param name="vcAdminname"></param>
        public void AdminLoginOut(string Adminname)
        {
            base.db.ExecuteNonQuery(CommandType.Text, "UPDATE Members SET IsOnline = " + (int)YesNo.No + " WHERE AdminName ='" + Adminname + "'");
        }

        /// <summary>
        /// 检测用户名是否存在
        /// </summary>
        /// <param name="adminname"></param>
        /// <returns></returns>
        public int CheckAdminNameForReg(string adminname, int selfID)
        {
            return base.db.ExecuteNonQuery(CommandType.Text, "SELECT COUNT(1) FROM Members WHERE AdminName='" + adminname + "' AND MemberID=" + selfID);
        }

        private void Initialization()
        {
            if (this._admincookie == null)
            {
                this._admincookie = Cookie.Get(ConfigurationManager.AppSettings["AdminCookieName"]);
                if (this._admincookie != null)
                {
                    if (this._admincookie.Values.Count != 1) return;
                    this._name = CommonUtils.UrlDecode(this._admincookie.Values["AdminName"]);
                    base.db.ExecuteNonQuery(CommandType.Text, "UPDATE [Members] SET LastLoginDate=GETDATE() WHERE AdminName ='" + this._name + "'");
                }
            }
            this._currenturl = this.RemoveA(CommonUtils.CurrentUrl);
        }

        private void AdminInit()
        {
            this.Initialization();
            if (this._admin != null) return;
            object TempAdmin = null;
            if (string.IsNullOrEmpty(this._name))
            {
                TempAdmin = SessionState.Get(ConfigurationManager.AppSettings["AdminSessionName"]);
                if (TempAdmin != null) SessionState.Remove(ConfigurationManager.AppSettings["AdminSessionName"]);
                this._admin = null;
                return;
            }
            this._admin = this.GetAdminEntityByAdminName(this._name);
            TempAdmin = SessionState.Get(ConfigurationManager.AppSettings["AdminSessionName"]);
            if (TempAdmin == null)
            {
                if (this._admin != null && this._admin.IsOnline == YesNo.Yes && this._admin.LastLoginIp == CommonUtils.UserIp && this._admin.IsDelete != YesNo.Yes)
                {
                    SessionState.Set(ConfigurationManager.AppSettings["AdminSessionName"], this._admin);
                }
                else
                {
                    SessionState.Remove(ConfigurationManager.AppSettings["AdminSessionName"]);
                }
            }
        }

        /// <summary>
        /// 检测权限操作项目
        /// </summary>
        /// <param name="pid">操作项编号</param>
        public bool CheckAdminPop(int pid)
        {
            if (!(this._admin != null && this._admin.PopeDomList != null && this._admin.PopeDomList.Count != 0 && this._admin.PopeDomList.ContainsKey(pid)))
            {
                new Terminator().Throw("您无权限访问改页面!", "", "," + ConfigurationManager.AppSettings["WebSite"]
                         + ConfigurationManager.AppSettings["ManagePath"]
                         + "login.aspx", ConfigurationManager.AppSettings["WebSite"] +
                         ConfigurationManager.AppSettings["ManagePath"] + "login.aspx", false);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检测管理员登录
        /// </summary>
        public bool CheckAdminLogin()
        {
            this.AdminInit();

            if (this._admin == null)
            {
                new Terminator().Throw("您还未登录后台!", "登录后台", "返回首页," + ConfigurationManager.AppSettings["WebSite"]
                         + ConfigurationManager.AppSettings["ManagePath"]
                         + "login.aspx", ConfigurationManager.AppSettings["WebSite"] +
                         ConfigurationManager.AppSettings["ManagePath"] + "login.aspx", false);
                return false;
            }

            return true;
        }


        private string RemoveA(string str)
        {
            if (str.IndexOf("?") > 0)
            {
                str = str.Substring(0, str.IndexOf("?"));
            }
            return str;
        }

        public void Logout()
        {
            this.AdminInit();
            this.AdminLoginOut(this._name);
            if (this._admincookie != null)
            {
                Cookie.Remove(this._admincookie);
            }
            if (this._admin != null)
            {
                DbCommand cmd = new SqlCommand("UPDATE [admin] SET IsOnline=" + (int)YesNo.No + " WHERE AdminName=@AdminName");
                base.db.AddInParameter(cmd, "@AdminName", DbType.String, this._admin.AdminName);
                base.db.ExecuteNonQuery(cmd);
                SessionState.Remove(ConfigurationManager.AppSettings["AdminSessionName"]);
            }
        }

        public MembersInfo adminInfo
        {
            get
            {
                this.AdminInit();
                if (this._admin == null) return new MembersInfo();
                return this._admin;
            }
        }

        public MembersInfo GetAdminInfo()
        {
            this.AdminInit();
            return this._admin;
        }


        private HttpCookie _admincookie = null;
        private string _name = string.Empty;
        private MembersInfo _admin = null;
        private string _currenturl = string.Empty;
    }
}
